package com.example.task1.ui.AllService.garbage;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.MultiAutoCompleteTextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.task1.R;
import com.example.task1.application.MyApplication;
import com.example.task1.bean.GarbageHomeBannerBean;
import com.example.task1.bean.GarbageSearchAutoBean;
import com.example.task1.bean.GarbageSortBean;
import com.example.task1.http.Api;
import com.example.task1.util.ApiResp;
import com.example.task1.util.CallBack;
import com.youth.banner.Banner;

import java.util.List;
import java.util.stream.Collectors;

import retrofit2.Call;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link GarbageHomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class GarbageHomeFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Banner banner;
    private Button btnSearch;
    private RecyclerView rvList;
    private GarbageSortAdapter garbageSortAdapter;
    private LinearLayoutManager linearLayoutManager;
    private MultiAutoCompleteTextView tvSearch;

    public GarbageHomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment GarbageHomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static GarbageHomeFragment newInstance(String param1, String param2) {
        GarbageHomeFragment fragment = new GarbageHomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    private int pageNum = 1;
    private boolean isTrue = true;

    private void loadCommentList() {
        rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (garbageSortAdapter.getItemCount() - 1 == linearLayoutManager.findLastVisibleItemPosition() && isTrue) {
                    isTrue = false;
                    initData();
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_garbage_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initData();
        loadCommentList();
        setAdapter();
        getBanner();
        Business();
    }

    private void Business() {
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = tvSearch.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    tvSearch.setError("不能为空");
                } else {
                    Intent intent = new Intent(getContext(), GarbageSearchActivity.class);
                    intent.putExtra("content", content);
                    getActivity().startActivity(intent);
                }
            }
        });
    }

    private void getBanner() {
        Call<ApiResp> call = Api.api().get(MyApplication.TOKEN, "/prod-api/api/garbage-classification/poster/list");
        Api.send(call, GarbageHomeBannerBean.class, new CallBack<GarbageHomeBannerBean>() {
            @Override
            public void success(GarbageHomeBannerBean data) {
                List<String> collect = data.getData().parallelStream().map(GarbageHomeBannerBean.DataDTO::getImgUrl).collect(Collectors.toList());
                MyApplication.banner(banner, collect);
            }

            @Override
            public void error(String msg) {

            }
        });
        Call<ApiResp> call1 = Api.api().get(MyApplication.TOKEN, "/prod-api/api/garbage-classification/garbage-classification/hot/list");
        Api.send(call1, GarbageSearchAutoBean.class, new CallBack<GarbageSearchAutoBean>() {
            @Override
            public void success(GarbageSearchAutoBean data) {
                List<String> collect = data.getData().parallelStream().map(GarbageSearchAutoBean.DataDTO::getKeyword).collect(Collectors.toList());
                ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_dropdown_item_1line, collect);
                tvSearch.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
                tvSearch.setAdapter(stringArrayAdapter);
            }

            @Override
            public void error(String msg) {

            }
        });
    }

    private void setAdapter() {
        garbageSortAdapter = new GarbageSortAdapter(getContext());
        linearLayoutManager = new LinearLayoutManager(getContext());
        rvList.setAdapter(garbageSortAdapter);
        rvList.setLayoutManager(linearLayoutManager);
    }

    private void initData() {
        Call<ApiResp> call = Api.api().get(MyApplication.TOKEN, "/prod-api/api/garbage-classification/garbage-classification/list?pageNum=" + pageNum + "&pageSize=10");
        Api.send(call, GarbageSortBean.class, new CallBack<GarbageSortBean>() {
            @Override
            public void success(GarbageSortBean data) {
                if (garbageSortAdapter.getData().size() < data.getTotal()) {
                    isTrue = true;
                    garbageSortAdapter.setData(data.getRows());
                    pageNum++;
                } else {
                    MyApplication.show("没有更多数据了");
                }
            }

            @Override
            public void error(String msg) {

            }
        });
    }

    private void initView(View view) {
        banner = view.findViewById(R.id.banner);
        btnSearch = view.findViewById(R.id.btn_search);
        rvList = view.findViewById(R.id.rv_list);
        tvSearch = view.findViewById(R.id.tv_search);
    }
}